package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.entity.system.EntityBiPlatform;
import com.loongtech.bi.manager.system.*;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * Author: yuri
 * Description: 渠道管理
 * Date: 11:45 2017/5/26
 */
@RestController
@Scope("prototype")
@RequestMapping("/channelconfig")
public class ChannelManagementAction {
    @Resource
    private Session session;
    @Resource
    private SysLogManager sysLogManager;
    @Resource
    private BiPlatformManager biPlatformManager;
    @Resource
    private BiChannelManager biChannelManager;
    @Resource
    private SysRoleChannelManager sysRoleChannelManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;


    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> search(@RequestParam Integer curPage, @RequestParam Integer pageSize, EntityBiChannel entity) {
        Page<List<EntityBiChannel>> list;
        try {
            list = biChannelManager.searchByCriteria(curPage, pageSize, entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    /**
     * 查询渠道平台下拉列表
     */
    @RequestMapping(value = "platlist.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria() {
        List<EntityBiPlatform> list;
        try {
            list = biPlatformManager.findByQuery("select id, name from EntityBiPlatform");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }

    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> add(EntityBiChannel entity) {
        try {
            List<EntityBiChannel> list = biChannelManager.findAll();
            ResultData<String> res = validate(true, entity, list);
            if (res != null) {
                return res;
            }
            biChannelManager.persist(entity);
            syncInfoLogManager.add(entity.getGameId().toString(), "insert into bi_channel(id,gameId,name,description,platformId,platName,updateAt) values" + "(" + "'" + entity.getId() + "','" + entity.getGameId() + "','" + entity.getName() + "','" + entity.getDescription() + "','" + entity.getPlatformId() + "','" + entity.getPlatName() + "'," + Time.currentTime() + ")");
            biPlatformManager.init();
            return ResultData.success();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntityBiChannel entity) {
        try {
            List<EntityBiChannel> list = biChannelManager.findAll();
            ResultData<String> res = validate(false, entity, list);
            if (res != null) {
                return res;
            }
            EntityBiChannel cur = biChannelManager.get(entity.getId());
            if (cur != null) {
                biChannelManager.merge(entity);
                syncInfoLogManager.add(entity.getGameId().toString(), "update bi_channel set gameId = '" + entity.getGameId() + "',name = '" + entity.getName() + "',description = '" + entity.getDescription() + "',platformId = '" + entity.getPlatformId() + "',platName = '" + entity.getPlatName()  + "',updateAt = " +  Time.currentTime() +" where id = '" + entity.getId() + "'");
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(String id) {
        try {
            EntityBiChannel cur = biChannelManager.get(id);
            if (cur != null) {
                if (!Utils.isEmptyStr(id)) {
                    List<String> cl = BiPlatformManager.CHANNEL_SERVERS_MAP.get(id);
                    if (cl != null && cl.size() > 0) {
                        return new ResultData<>(RetCode.eRChannelServer.getErrorcode(), RetCode.eRChannelServer.getErrorMsg());
                    }
                    //检查角色分配
                    if (sysRoleChannelManager.hasChannelAssignedNew(id)) {
                        return new ResultData<>(RetCode.eRChannelFuction.getErrorcode(), RetCode.eRChannelFuction.getErrorMsg());
                    }
                    biChannelManager.removeById(id);
                    syncInfoLogManager.add(cur.getGameId().toString(), "delete from bi_channel where id = '" + cur.getId() + "'");
                }
                biPlatformManager.init();
                return ResultData.success();
            } else {
                return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
    }

    private ResultData<String> validate(boolean isAdd, EntityBiChannel ebp, List<EntityBiChannel> ebpList) {
        if (ebp.getGameId() == null) {
            return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getId())) {
            return new ResultData<>(RetCode.eEmptyId.getErrorcode(), RetCode.eEmptyId.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getName())) {
            return new ResultData<>(RetCode.eNotExistName.getErrorcode(), RetCode.eNotExistName.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getPlatformId())) {
            return new ResultData<>(RetCode.eEmptyChannelPlat.getErrorcode(), RetCode.eEmptyChannelPlat.getErrorMsg());
        }
        if (isAdd) {  // 如果是添加，则ID与名称皆不能重
            for (EntityBiChannel e : ebpList) {
                if (ebp.getId().equals(e.getId()) && ebp.getGameId().equals(e.getGameId())) {
                    return new ResultData<>(RetCode.eIdExist.getErrorcode(), RetCode.eIdExist.getErrorMsg());
                }
                if (ebp.getName().equals(e.getName()) && ebp.getGameId().equals(e.getGameId())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        } else {  // 如果是修改，则名称不能重
            for (EntityBiChannel e : ebpList) {
                if (!ebp.getId().equals(e.getId()) && ebp.getName().equals(e.getName()) && ebp.getGameId().equals(e.getGameId())) {
                    return new ResultData<>(RetCode.eNameExist.getErrorcode(), RetCode.eNameExist.getErrorMsg());
                }
            }
        }
        return null;
    }
}
